﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Jinjia.Approve.Common.Enum;
using Jinjia.Approve.IRepository.JJFlow;
using Jinjia.Approve.IService.JJFlow;
using Jinjia.Approve.IService.JJFlow.Action;
using JinJia.Core.Base.Exceptions;

namespace Jinjia.Approve.Service.JJFlow.Action
{
    public class JJFLowActionReject : JJFlowActionGoTo, IJJFLowActionReject
    {
        private readonly IJJFlowNodeService _jjFlowNodeService;
        private readonly IFlowNodeReferenceRepository _flowNodeReferenceRepository;

        public JJFLowActionReject(IJJFlowInstanceService jjFlowInstanceService,
            IJJFlowTrackService jjFlowTrackService,
            IJJFlowNodeService jjFlowNodeService,
            IFlowNodeReferenceRepository flowNodeReferenceRepository) : base(jjFlowInstanceService,
            jjFlowTrackService)
        {
            _jjFlowNodeService = jjFlowNodeService;
            _flowNodeReferenceRepository = flowNodeReferenceRepository;
        }

        public async Task Reject(int instance_id, int user_id, string remark)
        {
            var instance = await CheckAndGetFlowInstanceById(instance_id);
            //获取当前操作的节点
            var current_node = await _jjFlowNodeService.GetNodeById(instance.CurrentNodeId);
            //查询参考轨迹
            var reference_list = await _flowNodeReferenceRepository.GetReferences(instance_id);
            var reference_model = reference_list.FirstOrDefault(x => x.node_id == current_node.id);
            if (reference_model == null)
            {
                throw new BusinessException("未找到该节点预计轨迹！");
            }

            reference_list = reference_list.Where(x => x.sequence > reference_model.sequence).ToList();
            var reference_node = reference_list.First();
            //断言可审核人
            AssertApprover(user_id, reference_node.node_id, instance.TemplateId, instance_id);
            //断言是否操作过此节点
            AssertExistTrack(user_id, reference_node.node_id, instance_id);
            //保存新节点到instance
            instance.CurrentNodeId = reference_node.node_id;
            instance.Status = "10";
            instance.UpdateUserId = user_id;
            instance.UpdateTime = DateTime.Now;
            await _jjFlowInstanceService.Save(instance);

            //获取已驳回的节点
            var next_node = await _jjFlowNodeService.GetNodeById(reference_node.node_id);
            //生成 track记录
            await RecordTrackInfo(next_node, instance_id, user_id, (int)EnumDb.JJFlowOperationTypeEnum.Reject, user_id, remark);
        }
    }
}